<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库编号">
              <a-input placeholder="请输入仓库编号" v-model="queryParam.warehouseCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库名称">
              <a-input placeholder="请输入仓库名称" v-model="queryParam.warehouseName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库类型">
              <j-dict-select-tag
                placeholder="请选择仓库类型"
                v-model="queryParam.warehouseType"
                dictCode="wms_warehouse_type"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" v-if="hasPermission('wms:warehouse:add')">新增</a-button>
      <a-button
        type="primary"
        icon="download"
        @click="handleExportXls('仓库信息')"
        v-if="hasPermission('wms:warehouse:export')"
        >导出</a-button
      >
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel" v-if="hasPermission('wms:warehouse:delete')">
            <a-icon type="delete" />删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)" v-if="hasPermission('wms:warehouse:edit')">编辑</a>
          <a-divider type="vertical" v-if="hasPermission('wms:warehouse:edit')" />
          <a-popconfirm
            title="确定删除吗?"
            @confirm="() => handleDelete(record.id)"
            v-if="hasPermission('wms:warehouse:delete')"
          >
            <a>删除</a>
          </a-popconfirm>
          <a-divider type="vertical" v-if="hasPermission('wms:warehouse:delete')" />
          <router-link
            :to="{ path: '/wms/warehouse/WarehouseLocationList', query: { warehouseId: record.id } }"
            v-if="hasPermission('wms:warehouse:location')"
          >
            <a>库位管理</a>
          </router-link>
        </span>

        <template slot="warehouseTypeSlot" slot-scope="text">
          <a-tag :color="getWarehouseTypeColor(text)">
            <j-dict-label :value="text" dictCode="wms_warehouse_type" />
          </a-tag>
        </template>

        <template slot="statusSlot" slot-scope="text">
          <a-tag :color="getStatusColor(text)">
            <j-dict-label :value="text" dictCode="wms_warehouse_status" />
          </a-tag>
        </template>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <warehouse-modal ref="modalForm" @ok="modalFormOk"></warehouse-modal>
  </a-card>
</template>

<script>
import WarehouseModal from './modules/WarehouseModal'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
import JDictLabel from '@/components/dict/JDictLabel.vue'
import { warehouseList, warehouseDelete, warehouseDeleteBatch, warehouseExport } from '@/api/wms'

export default {
  name: 'WarehouseList',
  mixins: [JeecgListMixin],
  components: {
    WarehouseModal,
    JDictSelectTag,
    JDictLabel,
  },
  created() {
    // 加载字典数据
    this.initDictConfig()

    // 页面加载时重置查询条件
    this.searchReset()
  },
  data() {
    return {
      description: '仓库管理',
      // 查询条件
      queryParam: {},
      // 权限数据
      permissionList: [],
      // 排序参数
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      // 分页参数
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '仓库编号',
          align: 'center',
          dataIndex: 'warehouseCode',
        },
        {
          title: '仓库名称',
          align: 'center',
          dataIndex: 'warehouseName',
        },
        {
          title: '仓库类型',
          align: 'center',
          dataIndex: 'warehouseType',
          scopedSlots: { customRender: 'warehouseTypeSlot' },
        },
        {
          title: '库位总数',
          align: 'center',
          dataIndex: 'locationCount',
        },
        {
          title: '负责人',
          align: 'center',
          dataIndex: 'manager',
        },
        {
          title: '联系电话',
          align: 'center',
          dataIndex: 'phone',
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          scopedSlots: { customRender: 'statusSlot' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/wms/warehouse/list',
        delete: '/wms/warehouse/delete',
        deleteBatch: '/wms/warehouse/deleteBatch',
        exportXlsUrl: warehouseExport,
      },
      // 仓库类型颜色映射
      warehouseTypeColors: {
        1: 'blue', // 型材
        2: 'green', // 配件
        3: 'orange', // 辅料
        4: 'purple', // 其他
        5: 'cyan', // 余料
        6: 'red', // 半料
        7: 'yellow', // 成品
        8: 'lime', // 半成品
      },
      // 状态颜色映射
      statusColors: {
        0: 'green', // 启用
        1: 'red', // 禁用
      },
    }
  },
  created() {
    this.loadPermissionData()
  },
  methods: {
    // 获取仓库类型对应的颜色
    getWarehouseTypeColor(type) {
      return this.warehouseTypeColors[type] || 'blue'
    },

    // 获取状态对应的颜色
    getStatusColor(status) {
      return this.statusColors[status] || 'blue'
    },

    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }

      // 构建查询参数
      const params = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        ...this.queryParam,
      }

      // 添加排序参数
      if (this.isorter.column) {
        params.column = this.isorter.column
        params.order = this.isorter.order
      }

      console.log('执行查询，参数:', params)
      this.loading = true
      warehouseList(params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            this.ipagination.total = res.result.total || 0
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    searchReset() {
      this.queryParam = {}
      this.loadData(1)
    },
    searchQuery() {
      console.log('执行查询，参数:', this.queryParam)
      this.loadData(1)
    },
    // 重写getQueryField方法，确保返回正确的字段列表
    getQueryField() {
      // 返回需要的字段，不包含多余的逗号
      return 'id,warehouseCode,warehouseName,warehouseType,locationCount,manager,phone,status'
    },
    handleDelete(id) {
      warehouseDelete({ id: id }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    batchDel() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择至少一条记录')
        return
      }
      let ids = this.selectedRowKeys.join(',')
      let that = this
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中数据?',
        onOk: function () {
          that.loading = true
          warehouseDeleteBatch({ ids: ids })
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.loading = false
            })
        },
      })
    },
    // 加载权限数据
    loadPermissionData() {
      // 获取用户权限列表
      const userAuth = JSON.parse(sessionStorage.getItem('LOGIN_USER_BUTTON_AUTH') || '[]')
      const sysAuth = JSON.parse(sessionStorage.getItem('SYS_BUTTON_AUTH') || '[]')

      // 合并权限数据
      this.permissionList = []

      // 处理用户权限
      userAuth.forEach((auth) => {
        if (typeof auth === 'string') {
          this.permissionList.push(auth)
        } else if (auth && auth.action) {
          this.permissionList.push(auth.action)
        }
      })

      // 处理系统权限
      sysAuth.forEach((auth) => {
        if (typeof auth === 'string') {
          if (!this.permissionList.includes(auth)) {
            this.permissionList.push(auth)
          }
        } else if (auth && auth.action) {
          if (!this.permissionList.includes(auth.action)) {
            this.permissionList.push(auth.action)
          }
        }
      })
    },

    // 判断是否有权限
    hasPermission(permission) {
      if (!permission) return true // 如果未指定权限，默认有权限

      // 检查权限列表中是否包含指定权限
      if (this.permissionList.includes(permission)) {
        return true
      }

      // 检查权限列表中是否包含以逗号分隔的多个权限
      for (let perm of this.permissionList) {
        if (perm && perm.includes(',')) {
          const perms = perm.split(',')
          if (perms.includes(permission)) {
            return true
          }
        }
      }

      return false
    },

    // 处理表格变化（排序、分页等）
    handleTableChange(pagination, filters, sorter) {
      // 处理排序
      if (sorter && sorter.field) {
        this.isorter.column = sorter.field
        this.isorter.order = sorter.order === 'ascend' ? 'asc' : 'desc'
      }

      // 处理分页
      this.ipagination = pagination

      // 重新加载数据
      this.loadData()
    },
  },
}
</script>

<style scoped>
.ant-card-body .table-operator {
  margin-bottom: 18px;
}
.ant-table-tbody .ant-table-row td {
  padding-top: 15px;
  padding-bottom: 15px;
}
.anty-row-operator button {
  margin: 0 5px;
}
.ant-btn-danger {
  background-color: #ffffff;
}
.ant-modal-cust-warp {
  height: 100%;
}
.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}
.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}
</style> 